import sys
import os
import os.path
import sys
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(current_dir)
sys.path.append("..")
import time
import _thread
from subprocess import *   

import queue

cmdOutQueue = queue.Queue()

def listenStdout(hFun):
    while True :
        #hFun.stdout.flush()
        lineStr = hFun.stdout.readline()
        #print lineStr
        cmdOutQueue.put(lineStr)
        
        if 'exit' in lineStr:  
            break    
def checkCommand():
    time.sleep(0.5)
    str = ""
    while not cmdOutQueue.empty():
        str = str + cmdOutQueue.get()
    if "OK" in str:
        return True
    else:
        return False

def checkRunCommand():
    time.sleep(0.5)
    str = ""
    str = str + cmdOutQueue.get()
    #while not cmdOutQueue.empty():
        #str = str + cmdOutQueue.get()
    if "OK" not in str:
        return False
    #print str
    str =  str.lstrip().rstrip()
    #str =  str.lstrip("command:")
    index = str.find("command:")
    if index < 0:
        return False    
    str = str[index+8:]
    retList = str.split()
    retDict = {}
    for key in retList:
        if ":" in key:
            temp =  key.split(":")
            retDict[temp[0]] = temp[1]
    #print retDict
    
def test():
    p = Popen("D:\\work\\cashtest\\x64\\Debug\\app.exe", stdin=PIPE,stdout=PIPE)
     #p = subprocess.Popen("D:\\work\\cashtest\\x64\\Debug\\app.exe", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #stdout = []
    _thread.start_new_thread(listenStdout, (p,))  
    
    p.stdin.write('load --cis_bottom E:\\20181207\\100V15\\1\\20183007_103037_0_Err0_LastErr0x0_Den0_Dir0_Ver0_SN0_cis_bottom.bmp \n')
    #time.sleep(0.1)
    if checkCommand():
        print("Load success")
    else:
        print("Load failed")

    #print "=============load \n"  
    #p.stdin.write('load -m test.raw\n') 
    #line = p.stdout.readline()
    #print "line=" + line
    p.stdin.write('run\n')

    checkRunCommand()
    
    time.sleep(0.5)
    while not cmdOutQueue.empty():
        print((cmdOutQueue.get()))
    p.stdin.write('bye\n')
    #print p.stdout.readline() 

    #time.sleep(0.1)
    
